<template>
  <div class="app-container">
    <el-card class="box-card" v-loading="loading">
      <div slot="header" class="clearfix">
        <span>考试结果</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
      </div>
      
      <div v-if="examResult">
        <!-- 成绩信息 -->
        <div class="result-header">
          <h2 class="exam-title">{{ examResult.examTitle }}</h2>
          <div class="score-display">
            <div class="score-value">{{ examResult.score }}</div>
            <div class="total-score">满分：{{ examResult.totalScore }}</div>
          </div>
        </div>
        
        <!-- 考试基本信息 -->
        <div class="exam-info">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">学科：</span>
                <span>{{ examResult.subjectName }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">教育阶段：</span>
                <span>{{ examResult.educationLevelName }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">学校：</span>
                <span>{{ examResult.schoolName }}</span>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">考试时间：</span>
                <span>{{ formatDateTime(examResult.examStartTime) }} ~ {{ formatDateTime(examResult.examEndTime) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">提交时间：</span>
                <span>{{ formatDateTime(examResult.submitTime) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="info-item">
                <span class="label">得分率：</span>
                <span>{{ calculateScoreRate(examResult.score, examResult.totalScore) }}%</span>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <el-divider></el-divider>
        
        <!-- 得分分析 -->
        <div class="score-analysis">
          <h3>得分分析</h3>
          <div class="statistics-container">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="statistics-item">
                  <div class="statistics-title">题型得分统计</div>
                  <el-table :data="calculateQuestionTypeData()" border>
                    <el-table-column prop="name" label="题型" align="center"></el-table-column>
                    <el-table-column prop="value" label="得分" align="center"></el-table-column>
                    <el-table-column prop="totalScore" label="总分" align="center"></el-table-column>
                    <el-table-column label="得分率" align="center">
                      <template slot-scope="scope">
                        {{ calculateScoreRate(scope.row.value, scope.row.totalScore) }}%
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="statistics-item">
                  <div class="statistics-title">正确率统计</div>
                  <el-card shadow="never" class="correct-rate-card">
                    <div class="correct-rate-item">
                      <span class="label">正确题数：</span>
                      <span class="value correct">{{ calculateCorrectRateData().correct }}</span>
                    </div>
                    <div class="correct-rate-item">
                      <span class="label">错误题数：</span>
                      <span class="value wrong">{{ calculateCorrectRateData().wrong }}</span>
                    </div>
                    <div class="correct-rate-item">
                      <span class="label">正确率：</span>
                      <span class="value">{{ calculateCorrectRate() }}%</span>
                    </div>
                  </el-card>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        
        <el-divider></el-divider>
        
        <!-- 答题详情 -->
        <div class="answer-details">
          <h3>答题详情</h3>
          
          <div v-for="(section, sectionIndex) in sections" :key="sectionIndex" class="question-section">
            <h4 v-if="section.questions.length > 0" class="section-title">{{ section.name }}</h4>
            
            <div v-for="(question, questionIndex) in section.questions" :key="questionIndex" class="question-item">
              <div class="question-header">
                <div class="question-title">
                  <span class="question-index">{{ sectionIndex + 1 }}-{{ questionIndex + 1 }}.</span>
                  <span v-html="question.content"></span>
                  <span class="question-score">（{{ question.score }}分）</span>
                  <el-tag size="mini" :type="question.isCorrect ? 'success' : 'danger'" class="result-tag">
                    {{ question.isCorrect ? '正确' : '错误' }}
                  </el-tag>
                </div>
              </div>
              
              <!-- 选项（单选题和多选题） -->
              <div v-if="question.questionType === 1 || question.questionType === 2" class="question-options">
                <div v-for="(option, optionIndex) in parseOptions(question.options)" :key="optionIndex" class="option-item">
                  <span class="option-key">{{ option.key }}.</span>
                  <span 
                    class="option-content" 
                    v-html="option.content"
                    :class="{
                      'correct-option': isCorrectOption(question, option.key),
                      'wrong-option': isWrongOption(question, option.key)
                    }">
                  </span>
                </div>
              </div>
              
              <!-- 判断题 -->
              <div v-if="question.questionType === 3" class="question-options">
                <div class="option-item" :class="{'correct-option': question.answer === 'true', 'wrong-option': question.answer === 'true' && question.userAnswer !== 'true'}">
                  <span>正确</span>
                </div>
                <div class="option-item" :class="{'correct-option': question.answer === 'false', 'wrong-option': question.answer === 'false' && question.userAnswer !== 'false'}">
                  <span>错误</span>
                </div>
              </div>
              
              <!-- 填空题 -->
              <div v-if="question.questionType === 4" class="question-blanks">
                <div v-for="(blank, blankIndex) in parseBlanks(question.answer)" :key="blankIndex" class="blank-item">
                  <div class="user-answer">
                    <span class="blank-label">您的答案（空{{ blankIndex + 1 }}）：</span>
                    <span class="blank-text" :class="{'correct-answer': isBlankCorrect(question, blankIndex), 'wrong-answer': !isBlankCorrect(question, blankIndex)}">
                      {{ getUserBlankAnswer(question, blankIndex) || '未作答' }}
                    </span>
                  </div>
                  <div class="correct-answer">
                    <span class="blank-label">正确答案：</span>
                    <span class="blank-text">{{ blank }}</span>
                  </div>
                </div>
              </div>
              
              <!-- 简答题 -->
              <div v-if="question.questionType === 5" class="question-essay">
                <div class="user-answer">
                  <div class="answer-label">您的答案：</div>
                  <div class="answer-text" v-html="question.userAnswer || '未作答'"></div>
                </div>
                <div class="correct-answer">
                  <div class="answer-label">参考答案：</div>
                  <div class="answer-text" v-html="question.answer"></div>
                </div>
              </div>
              
              <!-- 解析 -->
              <div v-if="question.analysis" class="question-analysis">
                <div class="analysis-label">答案解析：</div>
                <div class="analysis-text" v-html="question.analysis"></div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="action-area">
          <el-button type="primary" @click="goBack">返回列表</el-button>
          <el-button type="success" @click="downloadResult">下载考试结果</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getExamResult, downloadExamResult } from '@/api/exam';

export default {
  name: 'StudentExamResult',
  data() {
    return {
      loading: false,
      examResult: null,
      sections: [
        { type: 1, name: '一、单选题', questions: [] },
        { type: 2, name: '二、多选题', questions: [] },
        { type: 3, name: '三、判断题', questions: [] },
        { type: 4, name: '四、填空题', questions: [] },
        { type: 5, name: '五、简答题', questions: [] }
      ]
    };
  },
  created() {
    this.getExamResult();
  },
  methods: {
    // 获取考试结果
    getExamResult() {
      this.loading = true;
      const resultId = this.$route.params.id;
      if (!resultId) {
        this.$message.error('结果ID不能为空');
        this.$router.push('/student/exams');
        return;
      }
      
      getExamResult(resultId).then(response => {
        this.examResult = response.data;
        
        // 按题型分组
        this.sections.forEach(section => {
          section.questions = [];
        });
        
        if (this.examResult.questions && this.examResult.questions.length > 0) {
          this.examResult.questions.forEach(question => {
            const section = this.sections.find(s => s.type === question.questionType);
            if (section) {
              section.questions.push(question);
            }
          });
        }
        
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取考试结果失败');
        this.$router.push('/student/exams');
      });
    },
    // 计算题型得分数据
    calculateQuestionTypeData() {
      const typeMap = {
        1: '单选题',
        2: '多选题',
        3: '判断题',
        4: '填空题',
        5: '简答题'
      };
      
      const typeScores = {};
      const typeTotalScores = {};
      
      if (!this.examResult || !this.examResult.questions) {
        return [];
      }
      
      this.examResult.questions.forEach(question => {
        const typeName = typeMap[question.questionType] || '其他';
        
        if (!typeScores[typeName]) {
          typeScores[typeName] = 0;
          typeTotalScores[typeName] = 0;
        }
        
        typeScores[typeName] += question.userScore || 0;
        typeTotalScores[typeName] += question.score;
      });
      
      return Object.keys(typeScores).map(typeName => ({
        name: typeName,
        value: typeScores[typeName],
        totalScore: typeTotalScores[typeName]
      }));
    },
    // 计算正确率数据
    calculateCorrectRateData() {
      let correct = 0;
      let wrong = 0;
      
      if (!this.examResult || !this.examResult.questions) {
        return { correct: 0, wrong: 0 };
      }
      
      this.examResult.questions.forEach(question => {
        if (question.isCorrect) {
          correct++;
        } else {
          wrong++;
        }
      });
      
      return { correct, wrong };
    },
    // 计算正确率百分比
    calculateCorrectRate() {
      const data = this.calculateCorrectRateData();
      const total = data.correct + data.wrong;
      if (total === 0) return 0;
      return Math.round((data.correct / total) * 100);
    },
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    // 计算得分率
    calculateScoreRate(score, totalScore) {
      if (!totalScore) return 0;
      return Math.round((score / totalScore) * 100);
    },
    // 解析选项
    parseOptions(optionsStr) {
      if (!optionsStr) return [];
      
      try {
        return JSON.parse(optionsStr);
      } catch (e) {
        console.error('解析选项失败', e);
        return [];
      }
    },
    // 解析填空题答案
    parseBlanks(answerStr) {
      if (!answerStr) return [];
      
      try {
        return JSON.parse(answerStr);
      } catch (e) {
        return [answerStr];
      }
    },
    // 解析用户填空题答案
    parseUserBlanks(answerStr) {
      if (!answerStr) return [];
      
      try {
        return JSON.parse(answerStr);
      } catch (e) {
        return [answerStr];
      }
    },
    // 判断选项是否为正确选项
    isCorrectOption(question, optionKey) {
      if (question.questionType === 1) {
        return question.answer === optionKey;
      } else if (question.questionType === 2) {
        const answers = question.answer.split(',');
        return answers.includes(optionKey);
      }
      return false;
    },
    // 判断选项是否为错误选择
    isWrongOption(question, optionKey) {
      if (question.questionType === 1) {
        return question.userAnswer === optionKey && question.answer !== optionKey;
      } else if (question.questionType === 2) {
        const userAnswers = question.userAnswer ? question.userAnswer.split(',') : [];
        const correctAnswers = question.answer.split(',');
        return userAnswers.includes(optionKey) && !correctAnswers.includes(optionKey);
      }
      return false;
    },
    // 判断填空是否正确
    isBlankCorrect(question, index) {
      const correctBlanks = this.parseBlanks(question.answer);
      const userBlanks = this.parseUserBlanks(question.userAnswer);
      
      if (index >= correctBlanks.length || index >= userBlanks.length) {
        return false;
      }
      
      return correctBlanks[index] === userBlanks[index];
    },
    // 获取用户填空答案
    getUserBlankAnswer(question, index) {
      const userBlanks = this.parseUserBlanks(question.userAnswer);
      
      if (index >= userBlanks.length) {
        return '';
      }
      
      return userBlanks[index];
    },
    // 返回列表
    goBack() {
      this.$router.push('/student/exams');
    },
    // 下载考试结果
    downloadResult() {
      const resultId = this.$route.params.id;
      downloadExamResult(resultId).then(response => {
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `考试结果_${this.examResult.examTitle}_${this.formatDateTime(new Date())}.pdf`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }).catch(() => {
        this.$message.error('下载考试结果失败');
      });
    }
  }
};
</script>

<style scoped>
.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.exam-title {
  font-size: 22px;
  margin: 0;
}

.score-display {
  text-align: center;
}

.score-value {
  font-size: 36px;
  font-weight: bold;
  color: #F56C6C;
}

.total-score {
  font-size: 14px;
  color: #606266;
}

.exam-info {
  margin: 20px 0;
}

.info-item {
  line-height: 24px;
  margin-bottom: 10px;
}

.label {
  font-weight: bold;
  color: #606266;
}

.score-analysis {
  margin: 20px 0;
}

.statistics-container {
  margin-top: 20px;
}

.statistics-item {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
}

.statistics-title {
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.correct-rate-card {
  padding: 10px;
}

.correct-rate-item {
  margin-bottom: 15px;
  font-size: 16px;
}

.correct-rate-item .value {
  font-weight: bold;
}

.correct-rate-item .correct {
  color: #67C23A;
}

.correct-rate-item .wrong {
  color: #F56C6C;
}

.section-title {
  font-size: 18px;
  margin: 20px 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.question-item {
  margin-bottom: 25px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.question-header {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.question-title {
  line-height: 1.6;
  flex: 1;
}

.question-index {
  font-weight: bold;
  margin-right: 5px;
}

.question-score {
  font-size: 14px;
  color: #409EFF;
  margin-left: 10px;
}

.result-tag {
  margin-left: 10px;
}

.question-options {
  margin-left: 20px;
  margin-bottom: 15px;
}

.option-item {
  margin-bottom: 10px;
  display: flex;
}

.option-key {
  font-weight: bold;
  margin-right: 10px;
  min-width: 20px;
}

.correct-option {
  color: #67C23A;
  font-weight: bold;
}

.wrong-option {
  color: #F56C6C;
  text-decoration: line-through;
}

.question-blanks {
  margin-left: 20px;
  margin-bottom: 15px;
}

.blank-item {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.user-answer {
  margin-bottom: 10px;
}

.blank-label {
  font-weight: bold;
  margin-right: 10px;
}

.correct-answer {
  color: #67C23A;
}

.correct-answer .blank-label {
  color: #606266;
}

.wrong-answer {
  color: #F56C6C;
  text-decoration: line-through;
}

.question-essay {
  margin-left: 20px;
  margin-bottom: 15px;
}

.answer-label {
  font-weight: bold;
  margin-bottom: 5px;
}

.answer-text {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  line-height: 1.6;
}

.question-analysis {
  margin-top: 15px;
  margin-left: 20px;
}

.analysis-label {
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.analysis-text {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  line-height: 1.6;
}

.action-area {
  margin-top: 30px;
  text-align: center;
}
</style> 